package com.gnerv.sylvanas.business.manage.operation;

import com.gnerv.sylvanas.framework.common.model.RestResult;
import com.gnerv.sylvanas.framework.common.model.RestResultCode;
import com.gnerv.sylvanas.framework.core.BaseCurrentAccount;
import com.gnerv.sylvanas.framework.core.exception.BusinessException;
import com.gnerv.sylvanas.business.manage.model.bo.OrgBO;
import com.gnerv.sylvanas.business.manage.model.dto.OrgDTO;
import com.gnerv.sylvanas.business.manage.model.dto.OrgTreeDTO;
import com.gnerv.sylvanas.business.manage.model.entity.Org;
import com.gnerv.sylvanas.business.manage.repository.mapper.OrgAccountMapper;
import com.gnerv.sylvanas.business.manage.storage.OrgStorageService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author Gnerv LiGen
 */
@Service
@AllArgsConstructor
public class OrgOperationService {

    private final OrgStorageService orgStorageService;
    private final OrgAccountMapper orgAccountMapper;
    private final BaseCurrentAccount baseCurrentAccount;

    
    public boolean create(OrgBO orgBO) {
        Org org = orgBO.toOrg();
        orgStorageService.insert(org);
        return true;
    }

    
    public boolean deleteByUkId(String ukId) {
        int count = orgStorageService.selectCountByParentUkId(ukId);
        if (count > 0) {
            throw new BusinessException("删除失败！存在下级机构！");
        }
        orgStorageService.deleteByUkId(ukId);
        return true;
    }

    
    public boolean updateByUkId(OrgBO orgBO) {
        Org org = orgBO.toOrg();
        orgStorageService.updateByUkId(org);
        return true;
    }

    
    public OrgDTO selectByUkId(String ukId) {
        return orgStorageService.selectByUkId(ukId);
    }

    
    public List<OrgDTO> selectListByName(String name) {
        return orgStorageService.selectListByName(name);
    }

    
    public List<OrgTreeDTO> selectListTreeByParentUkId(String parentUkId) {
        return orgStorageService.selectListTreeByParentUkId(parentUkId);
    }

    
    public List<OrgDTO> selectListByParentUkId(String parentUkId) {
        return orgStorageService.selectListByParentUkId(parentUkId);
    }

    
    public boolean bindAccount(String orgUkId, Set<String> accountUkIdList) {
        orgAccountMapper.insertOrgAccount(orgUkId, accountUkIdList, baseCurrentAccount.ukId());
        return true;
    }

    
    public boolean unbindAccount(String orgUkId) {
        orgAccountMapper.deleteByOrgUkId(orgUkId);
        return true;
    }

    
    public OrgDTO selectByAccountUkId(String accountUkId) {
        return orgStorageService.selectByAccountUkId(accountUkId);
    }

    
    public List<OrgTreeDTO> selectListTreeByAccountUkId(String accountUkId) {
        return orgStorageService.selectListTreeByAccountUkId(accountUkId);
    }


}




